package com.woniuxy.patrol.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.common.utils.ResponseUtil;
import com.woniuxy.patrol.mapper.PatrolPlanRouteMapper;
import com.woniuxy.patrol.pojo.PatrolPlanRoute;
import com.woniuxy.patrol.service.PatrolPlanRouteService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class PatrolPlanRouteServiceImpl implements PatrolPlanRouteService {

    @Resource
    private PatrolPlanRouteMapper planRouteMapper;

    @Override
    public List<Long> getRouteIdsByPlanId(Long planId) {
        return planRouteMapper.selectRouteIdsByPlanId(planId);
    }

    @Override
    public List<Long> getPlanIdsByRouteId(Long routeId) {
        return planRouteMapper.selectPlanIdsByRouteId(routeId);
    }

    @Override
    @Transactional
    public ResponseUtil addPlanRoute(PatrolPlanRoute planRoute) {
        // 参数校验
        if (planRoute.getPlanId() == null || planRoute.getRouteId() == null) {
            return ResponseUtil.error("计划ID和路线ID不能为空");
        }

        // 检查是否已存在关联
        QueryWrapper<PatrolPlanRoute> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("plan_id", planRoute.getPlanId())
                .eq("route_id", planRoute.getRouteId())
                .eq("is_delete", 1);
        if (planRouteMapper.selectCount(queryWrapper) > 0) {
            return ResponseUtil.error("该计划与路线已存在关联");
        }

        // 设置默认值
        planRoute.setIsDelete(1);
        planRoute.setCreateTime(new Date());
        planRoute.setUpdateTime(new Date());

        int result = planRouteMapper.insert(planRoute);
        if (result > 0) {
            return ResponseUtil.success("关联添加成功");
        }
        return ResponseUtil.error("关联添加失败");
    }

    @Override
    @Transactional
    public ResponseUtil deletePlanRoute(Long id) {
        // 逻辑删除
        PatrolPlanRoute planRoute = new PatrolPlanRoute();
        planRoute.setId(id);
        planRoute.setIsDelete(0);
        planRoute.setUpdateTime(new Date());

        int result = planRouteMapper.updateById(planRoute);
        if (result > 0) {
            return ResponseUtil.success("关联删除成功");
        }
        return ResponseUtil.error("关联删除失败");
    }
}